package com.qiaofang.applet.service.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.qiaofang.applet.common.base.MongoBaseService;
import com.qiaofang.applet.common.context.QfContextHolder;
import com.qiaofang.applet.common.dto.DataRequest;
import com.qiaofang.applet.common.exception.BusinessException;
import com.qiaofang.applet.common.util.RedisKeyUtil;
import com.qiaofang.applet.common.util.RedisUtil;
import com.qiaofang.applet.constants.BusinessConstants;
import com.qiaofang.applet.constants.EmployeeRolesConstants;
import com.qiaofang.applet.constants.MemberOperateTypeConstants;
import com.qiaofang.applet.constants.UpDownFlagConstants;
import com.qiaofang.applet.service.member.domain.Employee;
import com.qiaofang.applet.service.member.domain.Member;
import com.qiaofang.applet.service.member.domain.MemberFocus;
import com.qiaofang.applet.service.member.domain.MemberRemark;
import com.qiaofang.applet.service.member.repository.EmployeeRepository;
import com.qiaofang.applet.service.member.repository.MemberRepository;
import com.qiaofang.applet.service.member.service.AppointmentService;
import com.qiaofang.applet.service.member.service.DepartmentService;
import com.qiaofang.applet.service.member.service.EmployeePropertyService;
import com.qiaofang.applet.service.member.service.EmployeeService;
import com.qiaofang.applet.service.member.service.dto.*;
import com.qiaofang.applet.service.other.domain.CityCompany;
import com.qiaofang.applet.service.other.domain.Corporation;
import com.qiaofang.applet.service.other.domain.EmpShowRules;
import com.qiaofang.applet.service.other.domain.PropertyRole;
import com.qiaofang.applet.service.other.service.CityCompanyService;
import com.qiaofang.applet.service.other.service.CorporationService;
import com.qiaofang.applet.service.other.util.DateTypeUtil;
import com.qiaofang.applet.service.property.domain.FirsthandEstate;
import com.qiaofang.applet.service.property.domain.Property;
import com.qiaofang.applet.service.property.domain.PropertyRoles;
import com.qiaofang.applet.service.property.domain.RightsInterests;
import com.qiaofang.applet.service.property.repository.PropertyRolesRepository;
import com.qiaofang.applet.service.property.service.CommonService;
import com.qiaofang.applet.service.property.service.FirsthandEstateService;
import com.qiaofang.applet.service.property.service.PropertyService;
import com.qiaofang.applet.service.property.service.dto.*;
import com.sun.org.apache.bcel.internal.generic.SWITCH;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.stream.Collectors;

import static org.springframework.data.domain.Sort.Direction.ASC;
import static org.springframework.data.domain.Sort.Direction.DESC;

/**
 * @author daiyuxiang
 */
@Slf4j
@Service
public class EmployeeServiceImpl extends MongoBaseService<Employee, String> implements EmployeeService {

    private final EmployeeRepository employeeRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private PropertyService propertyService;

    @Autowired
    private FirsthandEstateService firsthandEstateService;

    @Autowired
    private CorporationService corporationService;

    @Autowired
    private CityCompanyService cityCompanyService;

    @Autowired
    private EmployeePropertyService employeePropertyService;

    @Autowired
    private AppointmentService appointmentService;

    @Autowired
    private CommonService commonService;

    @Autowired
    private PropertyRolesRepository propertyRolesRepository;

    private RestTemplate template;

    {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(30000);
        requestFactory.setReadTimeout(30000);
        template = new RestTemplate(requestFactory);
    }

    private static final String PRO_EMP_ORDER_API = "/api/dataprocessing/syncData/getProEmpOrder";

    @Autowired
    private MemberRepository memberRepository;


    @Autowired
    public EmployeeServiceImpl(EmployeeRepository employeeRepository) {
        super(employeeRepository);
        this.employeeRepository = employeeRepository;
    }

    @Override
    public Page<Employee> findAllByParams(EmployeeQueryDto query, Pageable pageable) {

        Query queryParam = new Query();
        Criteria criteria = new Criteria();
        if (StringUtils.isNotBlank(query.getCorporationCode())) {
            criteria.and("corporationCode").is(query.getCorporationCode());
        }
        if (StringUtils.isNotBlank(query.getCityCode())) {
            criteria.and("cityCode").is(query.getCityCode());
        } else if (!CollectionUtils.isEmpty(query.getCityCodes())){
            criteria.and("cityCode").in(query.getCityCodes());
        }
        if (query.getRecommend() != null && query.getRecommend()) {
            criteria.and("recommend").is(true);
        }
        if (!CollectionUtils.isEmpty(query.getEmployeeUniqueUuids())) {
            criteria.and("employeeUniqueUuid").in(query.getEmployeeUniqueUuids());
        }
        if (StringUtils.isNotBlank(query.getEmployeeName())) {
            criteria.and("employeeName").regex(".*?" + query.getEmployeeName() + ".*");
        }
        queryParam.addCriteria(criteria);
        long count = mongoTemplate.count(queryParam, Employee.class);
        queryParam.with(pageable);
        List<Employee> employees = new ArrayList<>();
        if (count > 0) {
            employees = mongoTemplate.find(queryParam, Employee.class);
        }
        return PageableExecutionUtils.getPage(employees, pageable, () -> count);
    }

    @Override
    public Page<EmployeeListDto> convertDomainToListDto(Page<Employee> employeePage, String corporationCode) {
        List<EmployeeListDto> content = new ArrayList<>();

        if (employeePage.getTotalElements() > 0) {
            List<Employee> employeeList = employeePage.getContent();
            for (Employee employee : employeeList) {
                content.add(domainToListDto(employee));
            }
        }

        return PageableExecutionUtils.getPage(content, employeePage.getPageable(), () -> employeePage.getTotalElements());
    }

    @Override
    public Page<EmployeeListDto> convertDomainToListDto(Page<Employee> employeePage, long total) {
        List<EmployeeListDto> content = new ArrayList<>();

        if (employeePage.getTotalElements() > 0) {
            List<Employee> employeeList = employeePage.getContent();
            for (Employee employee : employeeList) {
                content.add(domainToListDto(employee));
            }
        }

        return PageableExecutionUtils.getPage(content, employeePage.getPageable(), () -> total);
    }

    @Override
    public Employee findByEmployeeUniqueUuid(String employeeUniqueUuid) {
        return employeeRepository.findByEmployeeUniqueUuid(employeeUniqueUuid);
    }

    @Override
    public void saveEmployee(Employee employee) {
        String id = employee.getId();
        if (StringUtils.isEmpty(id)) {
            return;
        }
        updateById(employee);
    }

    @Override
    public List<Employee> findAllByEmployeeUuidInAndCompanyUuid(List<String> uuidList, String companyUuid) {
        return employeeRepository.findAllByEmployeeUuidInAndCompanyUuid(uuidList, companyUuid);
    }

    @Override
    public List<Employee> findAllByEmployeeUuidIn(String corporationCode, List<String> uuidList) {
        return employeeRepository.findAllByEmployeeUniqueUuidInAndCorporationCode(uuidList, corporationCode);
    }

    @Override
    public List<EmployeeListDto> getEmployeeListDtoByPropety(Property property) {
        List<EmployeeListDto> result = new ArrayList<>();

        if (property != null) {
            List<String> employeeUuidList = new ArrayList<>();
            if (StringUtils.isNotBlank(property.getEmployeeUuid1())) {
                employeeUuidList.add(property.getEmployeeUuid1());
            }
            if (StringUtils.isNotBlank(property.getEmployeeUuid2())) {
                employeeUuidList.add(property.getEmployeeUuid2());
            }
            if (StringUtils.isNotBlank(property.getEmployeeUuid3())) {
                employeeUuidList.add(property.getEmployeeUuid3());
            }

            if (CollectionUtils.isEmpty(employeeUuidList)) {
                return result;
            }

            List<Employee> employeeList = this.findAllByEmployeeUuidInAndCompanyUuid(employeeUuidList, property.getCompanyUuid());

            result = employeeList.stream().map(this::domainToListDto).collect(Collectors.toList());
        }

        return result;
    }

    @Override
    public List<EmployeeListDto> getEmployeeListDtoByFirsthandEstate(FirsthandEstate firsthandEstate) {
        List<EmployeeListDto> result = new ArrayList<>();

        if (firsthandEstate != null) {
            List<String> employeeUuidList = new ArrayList<>();
            if (StringUtils.isNotBlank(firsthandEstate.getEmployeeUuid1())) {
                employeeUuidList.add(firsthandEstate.getEmployeeUuid1());
            }
            if (StringUtils.isNotBlank(firsthandEstate.getEmployeeUuid2())) {
                employeeUuidList.add(firsthandEstate.getEmployeeUuid2());
            }
            if (StringUtils.isNotBlank(firsthandEstate.getEmployeeUuid3())) {
                employeeUuidList.add(firsthandEstate.getEmployeeUuid3());
            }

            if (CollectionUtils.isEmpty(employeeUuidList)) {
                return result;
            }

            List<Employee> employeeList = this.findAllByEmployeeUuidInAndCompanyUuid(employeeUuidList, firsthandEstate.getCompanyUuid());

            result = employeeList.stream().map(this::domainToListDto).collect(Collectors.toList());
        }
        return result;
    }

    /**
     * 处理经纪人参数（客户端查询）
     *
     * @param employee
     * @return
     */
    @Override
    public EmployeeListDto domainToListDto(Employee employee) {
        if (employee == null) {
            return null;
        }
        EmployeeListDto employeeListDto = new EmployeeListDto();
        employeeListDto.setEmployeeUniqueUuid(employee.getEmployeeUniqueUuid());
        employeeListDto.setEmployeeUuid(employee.getEmployeeUuid());
        employeeListDto.setEmployeeName(employee.getEmployeeName());
        employeeListDto.setEmployeePhotoUrl(employee.getPhotoUrl());
        employeeListDto.setPositionName(employee.getPositionName());
        employeeListDto.setMobilePhone(employee.getMobilePhone());
        employeeListDto.setRecommend(employee.getRecommend());
        String deptName = employee.getDeptName();
        if (StringUtils.isEmpty(deptName)) {
            deptName = departmentService.getDeptName(employee.getCorporationCode(), employee.getCompanyUuid(), employee.getDeptUuid());
        }
        employeeListDto.setDeptName(deptName);
        employeeListDto.setRecommendDescribe(employee.getRecommendDescribe());
        return employeeListDto;
    }

    /**
     * 处理经纪人参数（后台管理系统查询）
     *
     * @param employee
     * @param cityMap
     * @return
     */
    @Override
    public EmployeeDetailDto domainToDetailDto(Employee employee, Map<String, String> cityMap) {
        if (employee == null) {
            return null;
        }
        EmployeeDetailDto employeeDetailDto = new EmployeeDetailDto();
        employeeDetailDto.setId(employee.getId());
        employeeDetailDto.setEmployeeUniqueUuid(employee.getEmployeeUniqueUuid());
        employeeDetailDto.setEmployeeName(employee.getEmployeeName());
        employeeDetailDto.setEmployeePhotoUrl(employee.getPhotoUrl());
        employeeDetailDto.setPositionName(employee.getPositionName());
        employeeDetailDto.setGender(employee.getGender());
        employeeDetailDto.setMobilePhone(employee.getMobilePhone());
        employeeDetailDto.setEmployeeStatus(employee.getEmployeeStatus());
        employeeDetailDto.setRecommend(employee.getRecommend());
        employeeDetailDto.setRecommendDescribe(employee.getRecommendDescribe());
        employeeDetailDto.setCityCode(employee.getCityCode());
        String deptName = employee.getDeptName();
        if (StringUtils.isEmpty(deptName)) {
            deptName = departmentService.getDeptName(employee.getCorporationCode(), employee.getCompanyUuid(), employee.getDeptUuid());
        }
        employeeDetailDto.setDeptName(deptName);
        employeeDetailDto.setCityName(cityMap.get(employee.getCityCode()));
        employeeDetailDto.setLabelUuidList(employee.getLabelUuidList());

        return employeeDetailDto;
    }

    @Override
    public List<Employee> findByCorporationCodeAndMobilePhone(String corporationCode, String phone) {
        return employeeRepository.findByCorporationCodeAndMobilePhone(corporationCode, phone);
    }

    @Override
    public ShowEmpUuidDto getEmployeeUuidDtoByProperty(String propertyUniqueUuid) {
        ShowEmpUuidDto empUuidDto = new ShowEmpUuidDto();
        Property property = propertyService.findByPropertyUniqueUuid(propertyUniqueUuid);
        if (property == null) {
            return empUuidDto;
        }
        String companyUuid = property.getCompanyUuid();
        empUuidDto.setCompanyUuid(companyUuid);
        empUuidDto.setEmployeeUuid1(property.getEmployeeUuid1());
        String uuidArr[] = {property.getEmployeeUuid1(), property.getEmployeeUuid2(), property.getEmployeeUuid3()};
        empUuidDto.setEmployeeUuidList(Arrays.asList(uuidArr));
        empUuidDto.setFixedEmployeeUuid(empUuidDto.getEmployeeUuid1());
        CityCompany company = cityCompanyService.getCompanyByUuid(companyUuid);
        EmpShowRules propertyShowRules = company.getPropertyShowRules();
        if (propertyShowRules.getShowStrategy() == 1) {
            processAndSortEmp(empUuidDto, property, propertyShowRules);
        } else {
            orderRuleList(empUuidDto, property, companyUuid, propertyShowRules);
        }
        return empUuidDto;
    }


    @Override
    public PropertyEmpDto getEmployeeDtoByProperty(String propertyUniqueUuid) {
        PropertyEmpDto propertyEmpDto = new PropertyEmpDto();

        if (commonService.isV20Corporation()) {
            return getV20EmployeeDtoByProperty(propertyUniqueUuid);
        }

        ShowEmpUuidDto empUuidDto = getEmployeeUuidDtoByProperty(propertyUniqueUuid);
        String companyUuid = empUuidDto.getCompanyUuid();
        List<String> employeeUuidList = empUuidDto.getEmployeeUuidList();
        String fixedEmployeeUuid = empUuidDto.getFixedEmployeeUuid();

        //获取固定展示位经纪人
        Employee fixedEmployee = employeeRepository.findByCompanyUuidAndEmployeeUuid(companyUuid, fixedEmployeeUuid);
        if (fixedEmployee == null) {
            fixedEmployee = employeeRepository.findByCompanyUuidAndEmployeeUuid(companyUuid, empUuidDto.getEmployeeUuid1());
        }
        propertyEmpDto.setEmployeeListDto(domainToListDto(fixedEmployee));

        Query query = new Query().addCriteria(Criteria.where("companyUuid").is(companyUuid));
        query.addCriteria(Criteria.where("employeeUuid").in(employeeUuidList));
        List<Employee> employeeList = mongoTemplate.find(query, Employee.class);
        if (!CollectionUtils.isEmpty(employeeList)) {
            List<EmployeeListDto> employeeListDtos = new ArrayList<>(employeeList.size());
            Map<String, Employee> employeeMap = employeeList.stream().collect(Collectors.toMap(Employee::getEmployeeUuid, a -> a, (k1, k2) -> k1));
            for (String employeeUuid : employeeUuidList) {
                Employee employee = employeeMap.get(employeeUuid);
                if (employee == null) {
                    continue;
                }
                employeeListDtos.add(domainToListDto(employee));
                employeeMap.remove(employeeUuid);
            }
            propertyEmpDto.setEmployeeListDtos(employeeListDtos);
        }

        return propertyEmpDto;
    }

    @Override
    public ShowEmpUuidDto getV20EmployeeUuidDtoByProperty(String propertyUniqueUuid) {
        /**
         * 这里因为20的营销uuid原因，导致在这里面需要将营销uuid转成employeeUuid出去
         */
        ShowEmpUuidDto empUuidDto = new ShowEmpUuidDto();
        Property property = propertyService.findByPropertyUniqueUuid(propertyUniqueUuid);
        if (property == null) {
            throw new BusinessException("房源不存在");
        }
        PropertyRoles propertyRoles = propertyRolesRepository.findFirstByPropertyUniqueUuidOrderByUpdateTimeDesc(propertyUniqueUuid);
        if (propertyRoles == null) {
            throw new BusinessException("该房源暂无相关人");
        }
        //获取公司相关人配置
        CityCompany cityCompany = cityCompanyService.getCompanyByUuid(property.getCompanyUuid());
        EmpShowRules propertyShowRules = cityCompany.getPropertyShowRules();
        if (propertyShowRules == null || CollectionUtils.isEmpty(propertyShowRules.getRoleList())) {
            log.info("propertyShowRules is null or RoleList is null,companyUuid:{}", property.getCompanyUuid());
            throw new BusinessException("propertyShowRules is null or RoleList is null,companyUuid:{}");
        }
        empUuidDto.setCompanyUuid(cityCompany.getCompanyUuid());
        List<PropertyRole> roleList = propertyShowRules.getRoleList();
        //固定展示位
        List<String> alias = roleList.stream().filter(f -> f.isFixedShow()).map(PropertyRole::getRoleName).collect(Collectors.toList());
        //所有经纪人列表
        List<String> allAlias = roleList.stream()
                .filter(f -> f.isShowOrHide()).sorted(Comparator.comparing(PropertyRole::getSort))
                .map(PropertyRole::getRoleName).collect(Collectors.toList());

        //这里是对应的固定展示位和列表展示位的uuid类型
        List<String> aliasFix = EmployeeRolesConstants.getEmployeeUuidList(alias);
        List<String> AllaliasBySort = EmployeeRolesConstants.getEmployeeUuidList(Lists.newArrayList(allAlias));
        //所有相关方的uuid
        List<String> employeeUuidListByAlias = getEmployeeUuidListByAlias(AllaliasBySort, propertyRoles);
        employeeUuidListByAlias = employeeUuidListByAlias.stream().filter(item -> StringUtils.isNotEmpty(item)).distinct().collect(Collectors.toList());

        //在这里进行营销uuid--》employeeUuid
        employeeUuidListByAlias = Optional.ofNullable(employeeRepository.findAllByCompanyUuidAndMarketingEmployeeUuidIn(property.getCompanyUuid(), employeeUuidListByAlias))
                .orElseGet(Lists::newArrayList).stream().map(Employee::getEmployeeUuid).collect(Collectors.toList());

        empUuidDto.setEmployeeUuidList(employeeUuidListByAlias);
        //固定展示位的uuid
        List<String> employeeUuidListByAlias1 = getEmployeeUuidListByAlias(aliasFix, propertyRoles);
        employeeUuidListByAlias1 = employeeUuidListByAlias1.stream().filter(item -> StringUtils.isNotEmpty(item)).distinct().collect(Collectors.toList());

        //在这里进行营销uuid--》employeeUuid
        employeeUuidListByAlias1 = Optional.ofNullable(employeeRepository.findAllByCompanyUuidAndMarketingEmployeeUuidIn(property.getCompanyUuid(), employeeUuidListByAlias1))
                .orElseGet(Lists::newArrayList).stream().map(Employee::getEmployeeUuid).collect(Collectors.toList());

        if (!CollectionUtils.isEmpty(employeeUuidListByAlias1)){
            empUuidDto.setFixedEmployeeUuid(employeeUuidListByAlias1.get(0));
        }else if (CollectionUtils.isEmpty(employeeUuidListByAlias1) && !CollectionUtils.isEmpty(employeeUuidListByAlias)){
            empUuidDto.setFixedEmployeeUuid(employeeUuidListByAlias.get(0));
        }
        return empUuidDto;
    }


    @Override
    public PropertyEmpDto getV20EmployeeDtoByProperty(String propertyUniqueUuid){
        PropertyEmpDto propertyEmpDto = new PropertyEmpDto();
        Property property = propertyService.findByPropertyUniqueUuid(propertyUniqueUuid);
        if (property == null) {
            log.info("getV20EmployeeDtoByProperty error ,beacause property is null，propertyUniqueUuid:{}", propertyUniqueUuid);
            throw new BusinessException("getV20EmployeeDtoByProperty property is null");
        }
        PropertyRoles propertyRoles = propertyRolesRepository.findFirstByPropertyUniqueUuidOrderByUpdateTimeDesc(propertyUniqueUuid);
        if (propertyRoles == null) {
            throw new BusinessException("该房源暂无相关人");
        }
        //获取公司相关人配置
        CityCompany cityCompany = cityCompanyService.getCompanyByUuid(property.getCompanyUuid());
        EmpShowRules propertyShowRules = cityCompany.getPropertyShowRules();
        if (propertyShowRules == null || CollectionUtils.isEmpty(propertyShowRules.getRoleList())) {
            log.info("propertyShowRules is null or RoleList is null,companyUuid:{}", property.getCompanyUuid());
            throw new BusinessException("propertyShowRules is null or RoleList is null,companyUuid:{}");
        }
        List<PropertyRole> roleList = propertyShowRules.getRoleList();
        //固定展示位
        List<String> alias = roleList.stream().filter(f -> f.isFixedShow()).map(PropertyRole::getRoleName).collect(Collectors.toList());
        //所有经纪人列表
        List<String> allAlias = roleList.stream()
                .filter(f -> f.isShowOrHide()).sorted(Comparator.comparing(PropertyRole::getSort))
                .map(PropertyRole::getRoleName).collect(Collectors.toList());

        List<String> aliasFix = EmployeeRolesConstants.getEmployeeUuidList(alias);
        List<String> AllaliasBySort = EmployeeRolesConstants.getEmployeeUuidList(Lists.newArrayList(allAlias));
        //所有相关方uuid
        List<String> employeeUuidListByAlias = getEmployeeUuidListByAlias(AllaliasBySort, propertyRoles);
        employeeUuidListByAlias = employeeUuidListByAlias.stream().filter(item -> StringUtils.isNotEmpty(item)).distinct().collect(Collectors.toList());

        Query query = new Query().addCriteria(Criteria.where("companyUuid").is(property.getCompanyUuid()));
        query.addCriteria(Criteria.where("marketingEmployeeUuid").in(employeeUuidListByAlias));
        List<Employee> employeeList = mongoTemplate.find(query, Employee.class);
        if (!CollectionUtils.isEmpty(employeeList)) {
            List<EmployeeListDto> employeeListDtos = new ArrayList<>(employeeList.size());
            Map<String, Employee> employeeMap = employeeList.stream().collect(Collectors.toMap(Employee::getMarketingEmployeeUuid, a -> a, (k1, k2) -> k1));
            for (String marketingEmployeeUuid : employeeUuidListByAlias) {
                Employee employee = employeeMap.get(marketingEmployeeUuid);
                if (employee == null) {
                    continue;
                }
                employeeListDtos.add(domainToListDto(employee));
                employeeMap.remove(marketingEmployeeUuid);
            }
            propertyEmpDto.setEmployeeListDtos(employeeListDtos);
        }
        List<String> employeeUuidListByAlias1 = getEmployeeUuidListByAlias(aliasFix, propertyRoles);
        employeeUuidListByAlias1 = employeeUuidListByAlias1.stream().filter(item -> StringUtils.isNotEmpty(item)).distinct().collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(employeeUuidListByAlias1)){
            propertyEmpDto.setEmployeeListDto(domainToListDto(employeeRepository.findByCompanyUuidAndMarketingEmployeeUuid(property.getCompanyUuid(), employeeUuidListByAlias1.get(0))));
        }else if (CollectionUtils.isEmpty(employeeUuidListByAlias1) && !CollectionUtils.isEmpty(employeeUuidListByAlias)){
            propertyEmpDto.setEmployeeListDto(domainToListDto(employeeRepository.findByCompanyUuidAndMarketingEmployeeUuid(property.getCompanyUuid(), employeeUuidListByAlias.get(0))));
        }
        return propertyEmpDto;
    }

    private List<String> getEmployeeUuidListByAlias(List<String> alias, PropertyRoles propertyRoles) {
        List<String> strings = new ArrayList<>();
        for (String tempAlias : alias) {
            switch (tempAlias) {
                case "inputEmployeeUuid":
                    strings.add(propertyRoles.getInputEmployeeUuid());
                    break;
                case "guardianEmployeeUuid":
                    strings.add(propertyRoles.getGuardianEmployeeUuid());
                    break;
                case "surveyEmployeeUuid":
                    strings.add(propertyRoles.getSurveyEmployeeUuid());
                    break;
                case "promotionEmployeeUuid":
                    strings.add(propertyRoles.getPromotionEmployeeUuid());
                    break;
                case "entrustIndemnityEmployeeUuid":
                    strings.add(propertyRoles.getEntrustIndemnityEmployeeUuid());
                    break;
                case "keyEmployeeUuid":
                    strings.add(propertyRoles.getKeyEmployeeUuid());
                    break;
                case "vrUploaderEmployeeUuid":
                    strings.add(propertyRoles.getVrUploaderEmployeeUuid());
                    break;
                case "videoUploaderEmployeeUuid":
                    strings.add(propertyRoles.getVideoUploaderEmployeeUuid());
                    break;
            }
        }
        return strings;
    }

    @Override
    public ShowEmpUuidDto getEmployeeUuidDtoByFirsthand(String estateUniqueUuid) {
        ShowEmpUuidDto empUuidDto = new ShowEmpUuidDto();
        FirsthandEstate firsthandEstate = firsthandEstateService.findByEstateUniqueUuid(estateUniqueUuid);
        if (empUuidDto == null) {
            return empUuidDto;
        }
        String companyUuid = firsthandEstate.getCompanyUuid();
        empUuidDto.setCompanyUuid(companyUuid);
        empUuidDto.setEmployeeUuid1(firsthandEstate.getEmployeeUuid1());
        String uuidArr[] = {firsthandEstate.getEmployeeUuid1(), firsthandEstate.getEmployeeUuid2(), firsthandEstate.getEmployeeUuid3()};
        empUuidDto.setEmployeeUuidList(Arrays.asList(uuidArr));
        empUuidDto.setFixedEmployeeUuid(empUuidDto.getEmployeeUuid1());
        CityCompany company = cityCompanyService.getCompanyByUuid(companyUuid);
        EmpShowRules firsthandShowRules = company.getFirsthandShowRules();
        List<String> uuidList = new LinkedList<>();
        if (firsthandShowRules.getShowStrategy() == 1) {
            for (PropertyRole propertyRole : firsthandShowRules.getRoleList()) {
                if (propertyRole.getRoleId() == -1L) {
                    if (propertyRole.isFixedShow()) {
                        empUuidDto.setFixedEmployeeUuid(firsthandEstate.getEmployeeUuid1());
                    }
                    if (propertyRole.isShowOrHide()) {
                        uuidList.add(firsthandEstate.getEmployeeUuid1());
                    }
                } else if (propertyRole.getRoleId() == -2L) {
                    if (propertyRole.isFixedShow()) {
                        empUuidDto.setFixedEmployeeUuid(firsthandEstate.getEmployeeUuid2());
                    }
                    if (propertyRole.isShowOrHide()) {
                        uuidList.add(firsthandEstate.getEmployeeUuid2());
                    }
                } else if (propertyRole.getRoleId() == -3L) {
                    if (propertyRole.isFixedShow()) {
                        empUuidDto.setFixedEmployeeUuid(firsthandEstate.getEmployeeUuid3());
                    }
                    if (propertyRole.isShowOrHide()) {
                        uuidList.add(firsthandEstate.getEmployeeUuid3());
                    }
                }
            }
            if (!CollectionUtils.isEmpty(uuidList)) {
                empUuidDto.setEmployeeUuidList(uuidList);
            }
        } else {
            int showNum = firsthandShowRules.getAssignRule().getShowNum();
            uuidList = employeePropertyService.getPutAwayOrder(firsthandEstate.getEstateUniqueUuid(), companyUuid, showNum, 1);
            if (!CollectionUtils.isEmpty(uuidList)) {
                empUuidDto.setEmployeeUuidList(uuidList);
                empUuidDto.setFixedEmployeeUuid(uuidList.get(0));
            }
        }
        return empUuidDto;
    }

    @Override
    public PropertyEmpDto getEmployeeDtoByFirsthand(String estateUniqueUuid) {
        PropertyEmpDto firsthandEmpDto = new PropertyEmpDto();
        ShowEmpUuidDto empUuidDto = getEmployeeUuidDtoByFirsthand(estateUniqueUuid);
        String companyUuid = empUuidDto.getCompanyUuid();
        List<String> employeeUuidList = empUuidDto.getEmployeeUuidList();
        String fixedEmployeeUuid = empUuidDto.getFixedEmployeeUuid();

        //获取固定展示位经纪人
        Employee fixedEmployee = employeeRepository.findByCompanyUuidAndEmployeeUuid(companyUuid, fixedEmployeeUuid);
        if (fixedEmployee == null) {
            fixedEmployee = employeeRepository.findByCompanyUuidAndEmployeeUuid(companyUuid, empUuidDto.getEmployeeUuid1());
        }
        firsthandEmpDto.setEmployeeListDto(domainToListDto(fixedEmployee));

        Query query = new Query().addCriteria(Criteria.where("companyUuid").is(companyUuid));
        query.addCriteria(Criteria.where("employeeUuid").in(employeeUuidList));
        List<Employee> employeeList = mongoTemplate.find(query, Employee.class);
        if (!CollectionUtils.isEmpty(employeeList)) {
            List<EmployeeListDto> employeeListDtos = new ArrayList<>(employeeList.size());
            Map<String, Employee> employeeMap = employeeList.stream().collect(Collectors.toMap(Employee::getEmployeeUuid, a -> a, (k1, k2) -> k1));
            for (String employeeUuid : employeeUuidList) {
                Employee employee = employeeMap.get(employeeUuid);
                if (employee == null) {
                    continue;
                }
                employeeListDtos.add(domainToListDto(employee));
                employeeMap.remove(employeeUuid);
            }
            firsthandEmpDto.setEmployeeListDtos(employeeListDtos);
        }

        return firsthandEmpDto;
    }


    /**
     * 按房源角色展示策略
     *
     * @param empUuidDto
     * @param property
     * @param propertyShowRules
     */
    private void processAndSortEmp(ShowEmpUuidDto empUuidDto, Property property, EmpShowRules propertyShowRules) {
        List<RightsInterests> rightsInterestsList = property.getRightsInterestsList();
        Map<Long, PropertyRole> roleMap = propertyShowRules.getRoleList().stream().collect(Collectors.toMap(PropertyRole::getRoleId, a -> a, (k1, k2) -> k1));
        if (!CollectionUtils.isEmpty(roleMap)) {
            //记录uuid排序
            List<EmpUuidSortDto> sortDtoList = new LinkedList<>();

            //归属人1
            PropertyRole propertyRole1 = roleMap.get(-1L);
            if (propertyRole1 != null) {
                if (propertyRole1.isFixedShow()) {
                    empUuidDto.setFixedEmployeeUuid(property.getEmployeeUuid1());
                }
                if (propertyRole1.isShowOrHide()) {
                    sortDtoList.add(new EmpUuidSortDto(property.getEmployeeUuid1(), propertyRole1.getSort(), -1));
                }
            }

            //归属人2
            PropertyRole propertyRole2 = roleMap.get(-2L);
            if (propertyRole2 != null) {
                if (propertyRole2.isFixedShow()) {
                    empUuidDto.setFixedEmployeeUuid(property.getEmployeeUuid2());
                }
                if (propertyRole2.isShowOrHide()) {
                    sortDtoList.add(new EmpUuidSortDto(property.getEmployeeUuid2(), propertyRole2.getSort(), -2));
                }
            }

            //归属人3
            PropertyRole propertyRole3 = roleMap.get(-3L);
            if (propertyRole3 != null) {
                if (propertyRole3.isFixedShow()) {
                    empUuidDto.setFixedEmployeeUuid(property.getEmployeeUuid3());
                }
                if (propertyRole3.isShowOrHide()) {
                    sortDtoList.add(new EmpUuidSortDto(property.getEmployeeUuid3(), propertyRole3.getSort(), -3));
                }
            }


            //遍历房源权益集合
            if (!CollectionUtils.isEmpty(rightsInterestsList)) {
                for (RightsInterests rightsInterests : rightsInterestsList) {
                    PropertyRole propertyRole = roleMap.get(rightsInterests.getFieldId());
                    if (propertyRole == null) {
                        continue;
                    }
                    if (propertyRole.isFixedShow()) {
                        empUuidDto.setFixedEmployeeUuid(rightsInterests.getEmployeeUuid());
                    }
                    if (propertyRole.isShowOrHide()) {
                        sortDtoList.add(new EmpUuidSortDto(rightsInterests.getEmployeeUuid(), propertyRole.getSort(), propertyRole.getRoleId().intValue()));
                    }
                }
            }

            //排序规则：sort字段从小到大排列，sort相等时，按id（绝对值）从小到大排列
            if (!CollectionUtils.isEmpty(sortDtoList)) {
                Collections.sort(sortDtoList, new Comparator<EmpUuidSortDto>() {
                    @Override
                    public int compare(EmpUuidSortDto o1, EmpUuidSortDto o2) {
                        int i = o1.getSort() - o2.getSort();
                        if (i == 0) {
                            i = Math.abs(o1.getRoleId()) - Math.abs(o2.getRoleId());
                        }
                        return i;
                    }
                });
                List<String> employeeUuidList = new ArrayList<>(sortDtoList.size());
                Set<String> uuidSet = new HashSet<>();
                for (EmpUuidSortDto empUuidSortDto : sortDtoList) {
                    String employeeUuid = empUuidSortDto.getEmployeeUuid();
                    //去重、判空
                    if (StringUtils.isEmpty(employeeUuid) || uuidSet.contains(employeeUuid)){
                        continue;
                    }
                    employeeUuidList.add(employeeUuid);
                    uuidSet.add(employeeUuid);
                }
                empUuidDto.setEmployeeUuidList(employeeUuidList);
            }
        }
    }


    /**
     * 按指定规则展示策略
     *
     * @param empUuidDto
     * @param property
     * @param companyUuid
     * @param propertyShowRules
     */
    private void orderRuleList(ShowEmpUuidDto empUuidDto, Property property, String companyUuid, EmpShowRules propertyShowRules) {
        String empOrderKey = RedisKeyUtil.getPropertyEmpOrderKey(companyUuid);
        Object obj = redisUtil.hget(empOrderKey, property.getPropertyUuid());
        if (obj != null) {
            List<String> list = JSONObject.parseArray(JSONObject.toJSONString(obj), String.class);
            if (!CollectionUtils.isEmpty(list)) {
                empUuidDto.setEmployeeUuidList(list);
                empUuidDto.setFixedEmployeeUuid(list.get(0));
            }
            return;
        }
        int showNum = propertyShowRules.getAssignRule().getShowNum();
        int sortRule = propertyShowRules.getAssignRule().getSortRule();
        List<String> employeeUuidList;
        if (sortRule == 1) {
            employeeUuidList = employeePropertyService.getPutAwayOrder(property.getPropertyUniqueUuid(), companyUuid, showNum, 2);
        } else {
            Corporation corporation = corporationService.getCorporationByCorporationCode(property.getCorporationCode());
            DataProcessCommon dataProcessCommon = DataProcessCommon.builder()
                    .appId(corporation.getPullAppId())
                    .appKey(corporation.getPullAppKey())
                    .companyUuid(companyUuid)
                    .domain(corporation.getPullDomain())
                    .build();
            PropertyEmpOrderRequest empOrderRequest = PropertyEmpOrderRequest.builder()
                    .propertyUuid(property.getPropertyUuid())
                    .showNum(showNum)
                    .sortRule(sortRule)
                    .build();
            employeeUuidList = httpRequestData(empOrderRequest, dataProcessCommon, PRO_EMP_ORDER_API);
        }
        if (!CollectionUtils.isEmpty(employeeUuidList)) {
            empUuidDto.setEmployeeUuidList(employeeUuidList);
            empUuidDto.setFixedEmployeeUuid(employeeUuidList.get(0));
        }
        redisUtil.hsetDayEnd(empOrderKey, property.getPropertyUuid(), employeeUuidList);
    }


    private HttpHeaders getHeaders(DataProcessCommon syncCommon) {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        headers.add("X-AUTH-APP-ID", syncCommon.getAppId());
        headers.add("X-AUTH-KEY", syncCommon.getAppKey());
        headers.add("companyUuid", syncCommon.getCompanyUuid());
        log.info("========>headers:{}", JSON.toJSONString(headers));
        return headers;
    }

    private List<String> httpRequestData(PropertyEmpOrderRequest bodys, DataProcessCommon dataProcessCommon, String apiUrl) {
        HttpHeaders headers = getHeaders(dataProcessCommon);
        DataRequest dataRequest = new DataRequest();
        dataRequest.setParam(bodys);
        String url = dataProcessCommon.getDomain() + apiUrl;
        String result = null;
        log.info("sync params {},header {}", dataRequest, headers);
        try {
            result = template.postForObject(url, new HttpEntity<>(dataRequest, headers), String.class);
            log.info("sync result {}", result);
        } catch (Exception e) {
            log.error("httpRequest error", e);
        }

        if (Objects.isNull(result)) {
            return null;
        }
        JSONObject resultObject = JSON.parseObject(result);
        if (null == resultObject) {
            return null;
        }
        String responseCode = resultObject.getString("responseCode");
        if (!"1".equals(responseCode)) {
            String responseMessage = resultObject.getString("responseMessage");
            log.info("sync error {}", responseMessage);
            return null;
        }
        if (Objects.isNull(resultObject)) {
            return null;
        }
        JSONArray data = resultObject.getJSONArray("data");
        return data.toJavaList(String.class);
    }

    @Override
    public List<VisitorRecordsListDto> listVisitorRecords(String employeeUniqueUuid) {
        String corporationCode = QfContextHolder.getContext().getCorporationCode();
        Criteria criteria = new Criteria().and("corporationCode").is(corporationCode)
                .and("employeeUniqueUuid").is(employeeUniqueUuid)
                .and("businessType").ne(BusinessConstants.EMPLOYEE.getCode())
                .and("operateType").is(MemberOperateTypeConstants.EXPLORE.getValue())
                .and("createTime").gte(DateTypeUtil.getBeginOrAfterDay(new Date(), Calendar.DAY_OF_MONTH, -30));
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.sort(DESC, "createTime"),//分组前排序
                Aggregation.sort(ASC, "read"),//分组前排序
                Aggregation.group("memberId", "businessType", "businessUuid")
                        .count().as("count")
                        .first("memberId").as("memberId")
                        .first("memberName").as("memberName")
                        .first("estateName").as("estateName")
                        .first("houseType").as("houseType")
                        .first("mainImageUrl").as("mainImageUrl")
                        .first("square").as("square")
                        .first("read").as("read")
                        .first("createTime").as("createTime"),
                Aggregation.sort(DESC, "createTime")//分组后排序
        );
        AggregationResults result = mongoTemplate.aggregate(agg, "member_member_operate", VisitorRecordsListDto.class);
        List<VisitorRecordsListDto> visitorRecordsListDtos = result.getMappedResults();
        List<String> memberIds = Optional.ofNullable(visitorRecordsListDtos).orElseGet(Lists::newArrayList).stream().map(VisitorRecordsListDto::getMemberId).distinct().collect(Collectors.toList());
        List<Member> memberList = memberRepository.findAllByCorporationCodeAndIdIn(corporationCode, memberIds);
        Map<String, Member> memberMap = memberList.stream().collect(Collectors.toMap(Member::getId, a -> a, (k1, k2) -> k1));
        for (VisitorRecordsListDto recordsListDto : visitorRecordsListDtos) {
            Member mem = memberMap.get(recordsListDto.getMemberId());
            if (mem == null) {
                recordsListDto.setMemberName("未授权用户");
                continue;
            }
            recordsListDto.setMemberName(mem.getName());
            recordsListDto.setHeadPortrait(mem.getHeadPortrait());
        }
        return visitorRecordsListDtos;
    }

    @Override
    public List<VisitorRecordsSimpleDto> newVisitorRecords(String employeeUniqueUuid) {
        //获取该经纪人的所有客户备注，供后续组装参数
        Employee employee = employeeRepository.findByEmployeeUniqueUuid(employeeUniqueUuid);
        if (employee == null) {
            throw new BusinessException("经纪人不存在");
        }

        List<MemberRemark> remarkList = employee.getRemarkList();
        Map<String, String> remarkMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(remarkList)) {
            remarkMap = remarkList.stream().collect(Collectors.toMap(MemberRemark::getMemberId, MemberRemark::getRemark, (k1, k2) -> k1));
        }

        String corporationCode = QfContextHolder.getContext().getCorporationCode();
        Criteria criteria = new Criteria().and("corporationCode").is(corporationCode)
                .and("employeeUniqueUuid").is(employeeUniqueUuid)
                .and("operateType").is(MemberOperateTypeConstants.EXPLORE.getValue())
                .and("createTime").gte(DateTypeUtil.getBeginOrAfterDay(new Date(), Calendar.DAY_OF_MONTH, -30));
        Member member = memberRepository.findFirstByCorporationCodeAndEmployeeUniqueUuid(corporationCode, employeeUniqueUuid);
        Criteria criteriaFocus = Criteria.where("businessType").is("会员")
                .and("memberId").is(member.getId());
        Query query = new Query(criteriaFocus);
        //过滤已关注会员
        if (mongoTemplate.count(query, MemberFocus.class) > 0) {
            List<MemberFocus> list = mongoTemplate.find(query, MemberFocus.class);
            List<String> memberIdList = Optional.ofNullable(list).orElseGet(Lists::newArrayList).stream().map(MemberFocus::getBusinessUuid).distinct().collect(Collectors.toList());
            criteria.and("memberId").nin(memberIdList);
        }
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.sort(DESC, "createTime"),//分组前排序
                Aggregation.group("memberId").first("memberId").as("memberId")
                        .first("createTime").as("createTime"),
                Aggregation.sort(DESC, "createTime", "memberId"),//分组后排序
                Aggregation.limit(5)
        );
        AggregationResults result = mongoTemplate.aggregate(agg, "member_member_operate", VisitorRecordsSimpleDto.class);
        List<VisitorRecordsSimpleDto> visitorRecordsListDtos = result.getMappedResults();
        List<String> memberIds = Optional.ofNullable(visitorRecordsListDtos).orElseGet(Lists::newArrayList).stream().map(VisitorRecordsSimpleDto::getMemberId).distinct().collect(Collectors.toList());
        List<Member> memberList = memberRepository.findAllByCorporationCodeAndIdIn(corporationCode, memberIds);
        Map<String, Member> memberMap = memberList.stream().collect(Collectors.toMap(Member::getId, a -> a, (k1, k2) -> k1));
        for (VisitorRecordsSimpleDto recordsListDto : visitorRecordsListDtos) {
            Member mem = memberMap.get(recordsListDto.getMemberId());
            String remark = remarkMap.get(recordsListDto.getMemberId());
            recordsListDto.setMemberName(StringUtils.isNotEmpty(remark) ? remark : mem.getName());
            recordsListDto.setHeadPortrait(mem.getHeadPortrait());
        }
        return visitorRecordsListDtos;
    }

    @Override
    public Page<EmployeeListDto> getEmployeeList(EmployeeListQueryDto queryDto, Pageable pageable) {
        Query findQuery = createFindQuery(queryDto);
        long count = mongoTemplate.count(findQuery, Employee.class);
        List<Employee> employeeList = new LinkedList<>();
        if (count > 0) {
            employeeList = mongoTemplate.find(findQuery.with(pageable), Employee.class);
        }
        List<EmployeeListDto> dtoList = domainToListDtoList(employeeList);
        return PageableExecutionUtils.getPage(dtoList, pageable, () -> count);
    }

    @Override
    public List<EmployeeListDto> domainToListDtoList(List<Employee> employeeList) {
        List<EmployeeListDto> dtoList = new LinkedList<>();
        if (CollectionUtils.isEmpty(employeeList)){
            return dtoList;
        }
        Map<String, String> empLabelMap = appointmentService.getEmpLabelMap();
        for (Employee employee : employeeList) {
            EmployeeListDto dto = domainToListDto(employee);
            dto.setWorkAge(DateTypeUtil.getWorkAgeStr(employee.getAttendWorkTime()));
            dto.setLabelContentList(appointmentService.getLabelContentList(empLabelMap, employee.getLabelUuidList()));
            dtoList.add(dto);
        }
        return dtoList;
    }

    @Override
    public Map<String, EmpFansAndExchangeDto> getFansAndExchangeCount() {
        Criteria criteriaFans = Criteria.where("businessType").is(BusinessConstants.EMPLOYEE.getValue());
        Aggregation aggregationFans = Aggregation.newAggregation(Aggregation.match(criteriaFans),
                Aggregation.group("businessUuid")
                        .first("businessUuid").as("employeeUniqueUuid")
                        .count().as("focusByCount"));
        List<EmpFansAndExchangeDto> fansList = mongoTemplate.aggregate(aggregationFans, "member_member_focus", EmpFansAndExchangeDto.class).getMappedResults();
        Map<String, EmpFansAndExchangeDto> fansMap = fansList.stream().collect(Collectors.toMap(EmpFansAndExchangeDto::getEmployeeUniqueUuid, a -> a, (k1, k2) -> k1));

        Criteria criteriaExchange = Criteria.where("operateType").in(MemberOperateTypeConstants.CHAT.getValue(),MemberOperateTypeConstants.CALL.getValue());
        Aggregation aggregationExchange = Aggregation.newAggregation(Aggregation.match(criteriaExchange),
                Aggregation.group("employeeUniqueUuid")
                        .first("employeeUniqueUuid").as("employeeUniqueUuid")
                        .count().as("receptionCount"));
        List<EmpFansAndExchangeDto> exchangeList = mongoTemplate.aggregate(aggregationExchange, "member_member_operate", EmpFansAndExchangeDto.class).getMappedResults();
        Map<String, EmpFansAndExchangeDto> exchangeMap = exchangeList.stream().collect(Collectors.toMap(EmpFansAndExchangeDto::getEmployeeUniqueUuid, a -> a, (k1, k2) -> k1));
        Set<Map.Entry<String, EmpFansAndExchangeDto>> entries = exchangeMap.entrySet();
        for (Map.Entry<String, EmpFansAndExchangeDto> entry : entries) {
            String key = entry.getKey();
            EmpFansAndExchangeDto exchangeDto = entry.getValue();
            EmpFansAndExchangeDto fansDto = fansMap.get(key);
            if (fansDto != null){
                exchangeDto.setFocusByCount(fansDto.getFocusByCount());
                fansMap.remove(key);
            }
        }
        exchangeMap.putAll(fansMap);
        return exchangeMap;
    }

    @Override
    public List<ReportBaseDto> getEmpBaseInfo(String corporationCode, String companyUuid) {
        List<ReportBaseDto> list = new ArrayList<>();
        Criteria criteria = Criteria.where("corporationCode").is(corporationCode)
                .and("companyUuid").is(companyUuid);
        List<Employee> employeeList = mongoTemplate.find(new Query(criteria), Employee.class);
        if (!CollectionUtils.isEmpty(employeeList)) {
            Map<String, String> cityMap = cityCompanyService.getCityMap(corporationCode);
            Map<String, String> deptMap = departmentService.getDeptMap(corporationCode, companyUuid);
            for (Employee employee : employeeList) {
                String deptName = employee.getDeptName();
                list.add(ReportBaseDto.builder()
                        .employeeUniqueUuid(employee.getEmployeeUniqueUuid())
                        .employeeName(employee.getEmployeeName())
                        .cityCode(employee.getCityCode())
                        .cityName(cityMap.get(employee.getCityCode()))
                        .deptUuid(employee.getDeptUuid())
                        .deptName(StringUtils.isNotEmpty(deptName) ? deptName : deptMap.get(employee.getDeptUuid()))
                        .build());
            }
        }
        return list;
    }


    private Query createFindQuery(EmployeeListQueryDto queryDto) {
        Query query = new Query();
        Criteria criteria = Criteria.where("CorporationCode").is(QfContextHolder.getContext().getCorporationCode())
                .and("cityCode").is(QfContextHolder.getContext().getCityCode());
        String labelUuid = queryDto.getLabelUuid();
        String workAgeValue = queryDto.getWorkAgeValue();
        String sortOptionValue = queryDto.getSortOptionValue();
        if (StringUtils.isNotEmpty(labelUuid)) {
            criteria.and("labelUuidList").regex(labelUuid);
        }
        if (StringUtils.isNotEmpty(workAgeValue)) {
            switch (workAgeValue) {
                case "1":
                    criteria.and("attendWorkTime").gt(DateTypeUtil.getTodayInHistory(1));
                    break;
                case "2":
                    criteria.andOperator(Criteria.where("attendWorkTime").gt(DateTypeUtil.getTodayInHistory(2)),
                            Criteria.where("attendWorkTime").lte(DateTypeUtil.getTodayInHistory(1)));
                    break;
                case "2-5":
                    criteria.andOperator(Criteria.where("attendWorkTime").gt(DateTypeUtil.getTodayInHistory(5)),
                            Criteria.where("attendWorkTime").lte(DateTypeUtil.getTodayInHistory(2)));
                    break;
                case "5-10":
                    criteria.andOperator(Criteria.where("attendWorkTime").gt(DateTypeUtil.getTodayInHistory(10)),
                            Criteria.where("attendWorkTime").lte(DateTypeUtil.getTodayInHistory(5)));
                    break;
                case "10":
                    criteria.and("attendWorkTime").lte(DateTypeUtil.getTodayInHistory(10));
                    break;
            }
        }
        query.addCriteria(criteria);
        if (StringUtils.isNotEmpty(sortOptionValue)) {
            switch (sortOptionValue) {
                case "1":
                    query.with(Sort.by(Sort.Order.desc("tradeCount")));
                    break;
                case "2":
                    query.with(Sort.by(Sort.Order.desc("inspectionCount")));
                    break;
                case "3":
                    query.with(Sort.by(Sort.Order.desc("focusByCount")));
                    break;
                case "4":
                    query.with(Sort.by(Sort.Order.desc("receptionCount")));
                    break;
            }
        }
        query.with(Sort.by(Sort.Order.asc("joinDate")));
        return query;
    }

}
